(function() {
    var _requestIndex = 1;
    var _requestQueue = {}; // 等待响应的请求队列

    $.cometd.configure({
        url : location.protocol + "//" + location.host + "/cometd" // 写完整路径，才可以开启WebSocketTransport协议
    });

    $.cometd.handshake({}, function(handshakeReply) {
        $.cometd.subscribe('/response', function(message) {
            console.log("subscribe response", message);

            var _requestId = message.data.requestId;
            var _request = _requestQueue["request-" + _requestId];

            var _responseBody = message.data.result.value;

            _request.responseBody = _responseBody;
            _request.responseHandler(_request);

            delete _requestQueue["request-" + _requestId];
        }, function(subscribeReply) {
            console.log('subscribe subscribeReply', subscribeReply);
        });
    });

    var CometdTransporter = function(_request) {
        console.log("request", _request);

        var _requestId = _requestIndex++;
        _requestQueue["request-" + _requestId] = _request; // 加入队列等待回调

        var requestEntity = {
            "requestId" : _requestId,
            "interfaceName" : _request.interfaceName,
            "methodName" : _request.methodName,
            "args" : _request.args
        };

        $.cometd.publish('/request', requestEntity);
    };

    // 挂载根对象
    var _root = null;

    if (!!window) {
        _root = window; // 浏览器环境, 挂载到window
    } else if (!!wx) {
        _root = wx; // 微信小程序, 挂载到wx
    } else {
        throw "window or wx not found, contact the developer now";
    }

    _root.CometdTransporter = CometdTransporter;
})();